package pers.smalltown.authorize.wechat;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;

import pers.smalltown.authorize.consts.Consts;
import pers.smalltown.authorize.wechat.dto.WxAccessToken;

@CrossOrigin(origins="*")
@RestController
@RequestMapping("/wechatfunc")
public class WechatFunction {
	
	
	@SuppressWarnings("unchecked")
	@GetMapping("/userinfo")
	public Map<String, Object> getUserInfo(@RequestParam String openid) throws JsonMappingException, JsonProcessingException {
		RestTemplate restTemplate = new RestTemplate();
		restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
		Map<String, Object> result = new HashMap<>();
		WxAccessToken accessObj = (WxAccessToken)WxGlobalData.getWxOpenIdCache(openid);
		if (accessObj == null) {
			result.put("errmsg", "请重新登录");
		} else {
			String accessToken = accessObj.getAccessToken();
			ObjectMapper objMapper = new ObjectMapper();
			objMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
			String resultStr = restTemplate.getForObject(Consts.getWxUserInfoUri(accessToken, openid), String.class);
			System.out.println("resultStr:" + resultStr);
			result = (Map)objMapper.readValue(resultStr, Map.class);
			System.out.println("userinfo:" + result);
		}
		return result;
	}
}
